using System;
using System.Data;
using System.Data.OleDb;

namespace ClownFish
{
	public static class DataConverter
	{
		public static DataTable ExcelToTable(string excelFilePath)
		{
			return DataConverter.ExcelToTable(excelFilePath, 0);
		}

		public static DataTable ExcelToTable(string excelFilePath, int sheetIndex)
		{
			if (string.IsNullOrEmpty(excelFilePath))
			{
				throw new ArgumentNullException("excelFilePath");
			}
			string connectionString = excelFilePath.EndsWith("xls", StringComparison.OrdinalIgnoreCase) ? ("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + excelFilePath + ";Extended Properties=Excel 8.0;") : ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelFilePath + ";Extended Properties=Excel 12.0;");
			DataTable result;
			using (OleDbConnection oleDbConnection = new OleDbConnection(connectionString))
			{
				oleDbConnection.Open();
				DataTable oleDbSchemaTable = oleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[]
				{
					null,
					null,
					null,
					"TABLE"
				});
				if (sheetIndex >= 0)
				{
					if (sheetIndex >= oleDbSchemaTable.Rows.Count - 1)
					{
						throw new ArgumentOutOfRangeException("sheetIndex");
					}
					string cmdText = "select * from [" + oleDbSchemaTable.Rows[sheetIndex]["TABLE_NAME"] + "]";
					OleDbCommand oleDbCommand = new OleDbCommand(cmdText, oleDbConnection);
					using (OleDbDataReader oleDbDataReader = oleDbCommand.ExecuteReader())
					{
						DataTable dataTable = new DataTable();
						dataTable.Load(oleDbDataReader);
						oleDbDataReader.Close();
						result = dataTable;
						return result;
					}
				}
				result = oleDbSchemaTable;
			}
			return result;
		}

		public static DataTable ExcelToTable(string excelFilePath, string sheetName)
		{
			if (string.IsNullOrEmpty(excelFilePath))
			{
				throw new ArgumentNullException("excelFilePath");
			}
			if (string.IsNullOrEmpty(sheetName))
			{
				throw new ArgumentNullException("sheetName");
			}
			string connectionString = excelFilePath.EndsWith("xls", StringComparison.OrdinalIgnoreCase) ? ("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + excelFilePath + ";Extended Properties=Excel 8.0;") : ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelFilePath + ";Extended Properties=Excel 12.0;");
			DataTable result;
			using (OleDbConnection oleDbConnection = new OleDbConnection(connectionString))
			{
				oleDbConnection.Open();
				string cmdText = "select * from [" + sheetName + "]";
				OleDbCommand oleDbCommand = new OleDbCommand(cmdText, oleDbConnection);
				using (OleDbDataReader oleDbDataReader = oleDbCommand.ExecuteReader())
				{
					DataTable dataTable = new DataTable();
					dataTable.Load(oleDbDataReader);
					oleDbDataReader.Close();
					result = dataTable;
				}
			}
			return result;
		}
	}
}
